package handler

import (
	"bookSrv/dao"
	"bookSrv/models"
	pb "bookSrv/proto"
	"context"
	"encoding/json"
	"github.com/gomodule/redigo/redis"
)

type BookSrv struct{}

func (e *BookSrv) Nums(ctx context.Context, emp *pb.ReqEmp, resp *pb.Response) error {
	resp.Data.BookCount = dao.BookNums()
	resp.Data.ChapterCount = dao.ChapterNums()
	return nil
}

func (e *BookSrv) BookPage(ctx context.Context, req *pb.BookPageReq, resp *pb.BookPageResp) error {
	var book []models.BookInfo
	reply, _ := redis.Bytes(dao.GRD.Do("get", "book"))
	if len(reply) == 0 {
		book, _ = dao.BookPage(req.No, req.Size)
		marshal, _ := json.Marshal(book)
		dao.GRD.Do("set", "book", marshal, "EX", "100")
	} else {
		json.Unmarshal(reply, &book)
	}
	var res []pb.BookInfo
	for i := range book {
		info := pb.BookInfo{
			Id:         int64(book[i].Id),
			Author:     book[i].Author,
			Name:       book[i].Name,
			Tags:       book[i].Tags,
			Intro:      book[i].Intro,
			Kind:       book[i].Kind,
			Words:      float32(book[i].Words),
			ChapterNum: int64(book[i].ChapterNum),
			ClickCount: int64(book[i].ClickCount),
		}
		res = append(res, info)
	}
	resp.Total = 0

	return nil
}

func (e *BookSrv) ReadRank(ctx context.Context, emp *pb.ReqEmp, resp *pb.ReadRankResp) error {
	//TODO implement me
	panic("implement me")
}

func (e *BookSrv) BookStatic(ctx context.Context, emp *pb.ReqEmp, resp *pb.BookStaticResp) error {
	//TODO implement me
	panic("implement me")
}
